package com.weijian.demo1.service;

import com.weijian.demo1.entity.Document;
import com.weijian.demo1.mapper.DocumentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DocumentService {

    @Autowired
    private DocumentMapper documentMapper;

    public Document createDocument(Document document, Long userId) {
        document.setCreatedBy(userId);
        document.setLastModifiedBy(userId);
        document.setCreatedAt(LocalDateTime.now());
        document.setUpdatedAt(LocalDateTime.now());
        document.setVersion(1);
        documentMapper.insert(document);
        return document;
    }

    public List<Document> getDocumentsByTeam(Long teamId) {
        return documentMapper.findByTeamId(teamId);
    }

    public Document getDocumentById(Long id) {
        return documentMapper.findById(id);
    }

    public Document updateDocument(Long id, Document document) {
        document.setId(id);
        document.setUpdatedAt(LocalDateTime.now());
        documentMapper.update(document);
        return document;
    }

    public void updateDocumentContent(Long documentId, String content, Long userId) {
        Document document = documentMapper.findById(documentId);
        if (document != null) {
            document.setContent(content);
            document.setLastModifiedBy(userId);
            document.setUpdatedAt(LocalDateTime.now());
            document.setVersion(document.getVersion() + 1);
            documentMapper.update(document);
        }
    }

    public void deleteDocument(Long id) {
        documentMapper.delete(id);
    }
}